<template>
  <div>
    <el-container>
      <el-aside width="330px">
        <div class="left">
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="车位名：" style="margin-top: 30px">
              <el-input
                v-model="one"
                placeholder="请输入车位名"
                style="display: block; width: 300px"
                size="medium"
              ></el-input>
            </el-form-item>
            <el-form-item label="车位金额：" style="margin-top: 35px">
              <el-input
                v-model="two"
                placeholder="请输入车位金额"
                size="medium"
                style="display: block; width: 300px"
              ></el-input>
            </el-form-item>
            <el-form-item label="车位类型：" style="margin-top: 30px">
              <el-select
                v-model="three"
                placeholder="请选择车位类型"
                size="medium"
                style="width: 300px"
              >
                <el-option label="地下" :value="1"></el-option>
                <el-option label="地上" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="车位状态：" style="margin-top: 30px">
              <el-select
                v-model="four"
                placeholder="请选择车位状态"
                size="medium"
                style="width: 300px"
              >
                <el-option label="已有车" :value="1"></el-option>
                <el-option label="未有车" :value="2"></el-option>
              </el-select>
            </el-form-item>
            <div class="aa"></div>
            <el-form-item style="margin-top: 55px">
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="search"
                style="width: 137px; margin-left: 10px; font-size: 14px"
                >查询</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="chongzhi"
                style="width: 137px; font-size: 14px"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-aside>
      <el-main>
        <div class="right" style="position: relative">
          <h1 style="margin-bottom: 10px; font-size: 24px">车位列表</h1>
          <el-button
            type="success"
            style="
              position: absolute;
              right: 20px;
              top: 0px;
              font-size: 14px;
              width: 100px;
            "
            icon="el-icon-plus"
            @click="add"
            >新增</el-button
          >
          <el-table
            :data="tableData"
            stripe
            border
            style="width: 100%"
            v-loading="loading"
          >
            <el-table-column
              type="index"
              label="序号"
              align="center"
              width="70px"
            >
            </el-table-column>
            <el-table-column
              prop="parkname"
              label="车位名称"
              align="center"
              width="200px"
              sortable
            >
            </el-table-column>
            <el-table-column
              prop="parkpay"
              label="车位金额"
              align="center"
              sortable
              width="180px"
            >
            </el-table-column>
            <el-table-column label="车位类型" align="center" width="180px">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.parktype"
                  :active-value="1"
                  :inactive-value="2"
                  active-text="地上"
                  inactive-text="地下"
                  active-color="#409EFF"
                  inactive-color="#DCDFE6"
                  @change="switch1(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>

            <el-table-column label="车位状态" align="center" width="180px">
              <template slot-scope="scope">
                <el-switch
                  v-model="scope.row.parkstatus"
                  :active-value="1"
                  :inactive-value="2"
                  active-text="已有车"
                  inactive-text="未有车"
                  active-color="#409EFF"
                  inactive-color="#DCDFE6"
                  @change="switch2(scope.row)"
                >
                </el-switch>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  plain
                  icon="el-icon-share"
                  :disabled="scope.row.parkstatus == 1"
                  @click="fenpei(scope.row)"
                >
                  分配车位
                </el-button>

                <el-button
                  plain
                  icon="el-icon-edit"
                  style="color: rgb(98, 168, 234)"
                  @click="edit(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  plain
                  icon="el-icon-delete"
                  style="border-color: #fbc4c4"
                  @click="deletes(scope.row)"
                  >移除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 分页 -->
        <div style="display: flex; justify-content: flex-end">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage1"
            :page-sizes="[5, 9, 20, 30]"
            :page-size="this.pageNum"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            style="margin-top: 10px"
          >
          </el-pagination>
        </div>
      </el-main>
    </el-container>

    <!-- 遮罩 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form
        ref="form"
        :model="form2"
        label-width="80px"
        style="padding: 0 20px"
        :rules="rules"
      >
        <el-form-item label="车位名称" prop="parkname">
          <el-input v-model="form2.parkname" style="width: 600px"></el-input>
        </el-form-item>
        <el-form-item label="车位金额" prop="parkpay">
          <el-input v-model="form2.parkpay" style="width: 600px"></el-input>
        </el-form-item>
        <el-form-item label="车位类型" prop="parktype">
          <el-select
            v-model="form2.parktype"
            placeholder="请选择车位类型"
            style="width: 600px"
          >
            <el-option label="地下" :value="1"></el-option>
            <el-option label="地上" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="车位状态">
          <el-select
            v-model="form2.parkstatus"
            placeholder="请选择车位状态"
            style="width: 600px"
          >
            <el-option label="已有车" :value="1"></el-option>
            <el-option label="未有车" :value="2"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="tijiao" v-show="title == '添加车位'"
          >确 定</el-button
        >
        <el-button type="primary" @click="baocun" v-show="title == '编辑车位'"
          >保 存</el-button
        >
      </div>
    </el-dialog>

    <!-- 分配车位遮罩 -->
    <el-drawer
      title="车位分配"
      :visible.sync="drawer"
      :direction="direction"
      size="50%"
    >
      <el-table
        ref="multipleTable"
        :data="tableData2"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        border
        stripe
      >
        <!-- 保留多选框列 -->
        <el-table-column type="selection" width="50" align="center">
        </el-table-column>
        <el-table-column type="index" label="序号" width="70" align="center">
        </el-table-column>
        <el-table-column
          prop="username"
          label="用户账号"
          width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="homeaddress"
          label="家庭住址"
          width="200"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="type"
          label="类型"
          width="120"
          align="center"
          :formatter="statusFormatter"
        >
        </el-table-column>
        <el-table-column prop="parkname" label="车位" align="center">
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange2"
        @current-change="handleCurrentChange2"
        :current-page.sync="currentPage1"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pageNum2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total2"
        style="text-align: right; margin-top: 20px"
      >
      </el-pagination>
      <div class="btns" style="text-align: center; margin-top: 20px">
        <el-button
          @click="fpcwqx"
          style="width: 200px; margin-right: 50px; font-size: 14px"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="queren"
          style="width: 200px; font-size: 14px"
          >确认</el-button
        >
      </div>
    </el-drawer>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loading: true,
      title: "新增车位",
      dialogFormVisible: false,
      form: {
        parkname: null,
        parkpay: null,
        parktype: "",
        parkstatus: "",
      },
      form2: {
        parkname: "",
        parkpay: "",
        parktype: "",
        parkstatus: "",
      },
      id: null,

      tableData: [
        {
          parkname: null,
          parkpay: null,
          parktype: "",
          parkstatus: "",
        },
      ],
      tableData2: [],

      currentPage1: 1,
      total: 0,
      total2: 0,
      currPage: 0,
      pageNum: 9,
      currPage2: 0,
      pageNum2: 10,

      direction: "ltr",
      drawer: false,
      token: localStorage.getItem("token"),

      selectedRows: [], // 当前选中的行（数组形式）

      one: "",
      two: "",
      three: "",
      four: "",
      rules: {
        parkname: [
          { required: true, message: "车位名称不能为空", trigger: "blur" },
        ],
        parkpay: [
          { required: true, message: "车位金额不能为空", trigger: "blur" },
        ],
        parktype: [
          { required: true, message: "车位类型不能为空", trigger: "change" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getList2();
  },
  methods: {
    // 处理选中行变化事件
    handleSelectionChange(selection) {
      if (selection.length > 1) {
        // 如果选中了多行，则只保留最新选中的行
        this.$refs.multipleTable.clearSelection(); // 清除所有选中状态
        this.$refs.multipleTable.toggleRowSelection(
          selection[selection.length - 1],
          true
        ); // 选中最新的一行
      } else {
        this.selectedRows = selection; // 更新选中的行
      }
    },
    // 处理行点击事件
    handleRowClick(row) {
      this.$refs.multipleTable.clearSelection(); // 清除所有选中状态
      this.$refs.multipleTable.toggleRowSelection(row, true); // 选中当前行
    },
    // 确认按钮逻辑
    queren() {
      if (this.selectedRows.length > 0) {
        console.log("选中的行数据：", this.selectedRows[0]);
        // 这里可以添加确认后的逻辑
      } else {
        this.$message.warning("请先选择一行数据！");
      }
    },

    // 处理行点击事件
    handleRowClick(row) {
      this.selectedRow = row; // 记录选中的行
    },
    async getList() {
      let a = await this.$axios.get(
        "http://community.byesame.com/parking/getParkData?parkname=&parkpay=&parktype=&parkstatus=&currPage=" +
          this.currPage +
          "&pageNum=" +
          this.pageNum
      );
      console.log(a);
      this.tableData = a.data.data;
      this.total = a.data.total;
      setTimeout(() => {
        this.loading = false;
      }, 500);
    },

    async getList2() {
      let a = await this.$axios.get(
        "http://community.byesame.com/users/getUsersData?currPage=" +
          this.currPage2 +
          "&pageNum=" +
          this.pageNum2
      );
      console.log(a);
      this.tableData2 = a.data.data;
      this.total2 = a.data.total;
    },

    async switch1(row) {
      console.log(row);
      try {
        // 调用接口更新状态
        await this.$axios.post("/parking/editParkData", {
          u_id: row.id,
          parkname: row.parkname,
          parkpay: row.parkpay,
          parktype: row.parktype,
          parkstatus: row.parkstatus,
          token: sessionStorage.getItem("token"),
        });

        // 显示成功消息
        this.$message({
          type: "success",
          message: "更新成功",
        });

        // 刷新数据
        this.getList();
      } catch (error) {
        // 如果接口调用失败，恢复原来的状态
        if (row.parktype == 1) {
          row.parktype = 2;
        } else {
          row.parktype = 1;
        }

        // 显示错误消息
        this.$message({
          type: "error",
          message: "更新失败",
        });

        // 刷新数据
        this.getList();
      }
    },

    // 处理开关状态改变
    async switch2(row) {
      console.log(row);
      try {
        // 调用接口更新状态
        await this.$axios.post(
          "http://community.byesame.com/parking/editParkData",
          {
            u_id: row.id,
            parkname: row.parkname,
            parkpay: row.parkpay,
            parktype: row.parktype,
            parkstatus: row.parkstatus,
            token: sessionStorage.getItem("token"),
          }
        );
        // 显示成功消息
        this.$message({
          type: "success",
          message: "更新成功",
        });

        // 刷新数据
        this.getList();
      } catch (error) {
        // 如果接口调用失败，恢复原来的状态
        if (row.parkstatus == 1) {
          row.parkstatus = 2;
        } else {
          row.parkstatus = 1;
        }

        // 显示错误消息
        this.$message({
          type: "error",
          message: "更新失败",
        });

        // 刷新数据
        this.getList();
      }
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = val;
      this.getList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currPage = val - 1;
      this.getList();
    },
    handleSizeChange2(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum2 = val;
      this.getList2();
    },
    handleCurrentChange2(val) {
      console.log(`当前页: ${val}`);
      this.currPage2 = val - 1;
      this.getList2();
    },

    add() {
      this.title = "添加车位";
      this.dialogFormVisible = true;
      this.form2.parkname = "";
      this.form2.parkpay = "";
      // this.form2.parktype = "";
      // this.form2.parkstatus = "";
    },

    // 新增中的提交
    async tijiao() {
      let a = await this.$axios.post(
        "http://community.byesame.com/parking/addParkData",
        {
          parkname: this.form2.parkname,
          parkpay: this.form2.parkpay,
          parktype: this.form2.parktype,
          parkstatus: this.form2.parkstatus,
          token: this.token,
        }
      );
      console.log(a);
      this.dialogFormVisible = false;
      this.getList();
    },

    // 取消
    quxiao() {
      this.dialogFormVisible = false;
    },
    chongzhi1() {
      this.form2 = {};
    },

    // 编辑
    edit(row) {
      this.form2 = row;
      this.dialogFormVisible = true;
      this.title = "编辑车位";
      this.id = row.id;
    },
    async baocun() {
      let a = await this.$axios.post(
        "http://community.byesame.com/parking/editParkData",
        {
          u_id: this.id,
          parkname: this.form2.parkname,
          parkpay: this.form2.parkpay,
          parktype: this.form2.parktype,
          parkstatus: this.form2.parkstatus,
          token: this.token,
        }
      );
      console.log(a);
      this.dialogFormVisible = false;
      this.getList();
    },

    // 移除
    async deletes(row) {
      this.$confirm("此操作将永久删除该车位, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$axios
            .get(
              "http://community.byesame.com/parking/delParkData?id=" +
                row.id +
                "&token=" +
                this.token
            )
            .then((response) => {
              console.log(response);
              this.$message({
                message: "删除车位成功!",
                type: "success",
              });
              this.dialogFormVisible = false;
              this.getList();
            })
            .catch((error) => {
              console.error(error);
              this.$message({
                message: "删除车位失败, 请重试!",
                type: "error",
              });
            });
        })
        .catch(() => {
          this.$message({
            message: "已取消删除",
            type: "info",
          });
        });
    },

    // 格式化状态
    statusFormatter(row) {
      let type = row.type;
      if (type == 1) {
        return "管理员";
      } else {
        return "普通用户";
      }
    },

    // 分配车位
    fenpei(row) {
      this.drawer = true;
      this.form = row;
    },
    // 分配车位的取消
    fpcwqx() {
      this.drawer = false;
    },

    // 分配车位遮罩中的确认
    queren() {
      console.log(this.selectedRows);
      console.log("form", this.form);

      this.$confirm("确定分配该车位？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(async () => {
          try {
            const responseA = await this.$axios.post(
              "/users/updateParkStatus",
              {
                u_id: this.selectedRows[0].id,
                parkId: this.selectedRows[0].parkId,
                parkname: this.selectedRows[0].parkname,
                parkstatus: this.selectedRows[0].parkstatus,
                token: sessionStorage.getItem("token"),
              }
            );

            if (responseA.status !== 200) {
              throw new Error("更新车位状态失败：" + responseA.data.message);
            }

            const responseB = await this.$axios.post("/parking/editParkData", {
              u_id: this.form.id,
              parkname: this.selectedRows[0].parkname,
              parkpay: this.form.parkpay,
              parktype: this.form.parktype,
              parkstatus: this.selectedRows[0].parkstatus,
              token: sessionStorage.getItem("token"),
            });

            if (responseB.status !== 200) {
              throw new Error("编辑车位数据失败：" + responseB.data.message);
            }

            this.getList();
            this.$message({
              type: "success",
              message: "更新成功",
            });
            this.drawer = false;
          } catch (error) {
            console.error("发生错误：", error);

            this.$message({
              type: "error",
              message: error.message || "操作失败，请重试",
            });

            this.getList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消更新",
          });
        });
    },

    // 查询
    async search() {
      let a = await this.$axios.get(
        "http://community.byesame.com/parking/getParkData?parkname=" +
          this.one +
          "&parkpay=" +
          this.two +
          "&parktype=" +
          this.three +
          "&parkstatus=" +
          this.four +
          "&currPage=" +
          this.currPage +
          "&pageNum=" +
          this.pageNum
      );
      console.log(a);
      this.tableData = a.data.data;
      this.total = a.data.total;
    },

    // 重置
    chongzhi() {
      this.input1 = "";
      this.input2 = "";
      this.selectedStatus = "";
      this.getList();
    },
  },
};
</script>

<style scoped>
/* .left {
  width: 25%;
  height: 500px;
  padding: 30px 0;
} */
::v-deep .custom-header {
  background-color: #eef1f6 !important;
  color: rgb(31, 45, 61);
  font-size: 14px;
  font-weight: bold;
}
.aa {
  width: 300px;
  border: 0.1px solid #f3f3f3;
}
.xinzeng {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.xinzeng .box {
  width: 900px;
  height: 500px;
  background-color: #fff;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20px;
}

.fenpeichewei {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
}
.box2 {
  position: absolute;
  width: 800px;
  left: 0;
  top: 0;
  bottom: 0;
  background-color: white;
  z-index: 999;
  padding: 0 20px;
}

 .el-form-item .el-form-item__label {
  float: none !important;
}
 .el-form-item__content {
  margin-left: 0 !important;
}
</style>
